/**
 * 
 */
package com.shiplanet.aspect;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

import com.shiplanet.entity.Visitor;

/**
 * @author joesong
 *
 */
public class EmailAdvice {

	@Resource
	private MailSender mailSender;

	@Resource
	private SimpleMailMessage templateMessage;

	@Resource
	private TaskExecutor taskExecutor;

	private Logger logger = Logger.getLogger("EmailAdvice");

	public void synchronizedEmail(JoinPoint joinPoint) {

		logger.info("start synchronized email");
		
		Visitor visitor = (Visitor) joinPoint.getArgs()[0];

		// Create a thread safe "copy" of the template message and customize it
		SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
		msg.setSubject("A new visitor is coming!");
		msg.setText("Dear Staff, \n" + "A new visitor named "
				+ visitor.getName()
				+ " has just left his contact information.\n" + "name: "
				+ visitor.getName() + "\n" + "email: " + visitor.getEmail()
				+ "\n" + "phone: " + visitor.getPhone() + "\n" + "message: "
				+ visitor.getMessage());

		try {
			this.mailSender.send(msg);
			logger.info("an email has been sent");
		} catch (MailException ex) {
			logger.error(ex.getMessage());
		}
	}

	public void asynchronizedEmail(final JoinPoint joinPoint) {
		logger.info("start asynchronized email");
		taskExecutor.execute(new Runnable() {
			public void run() {
				synchronizedEmail(joinPoint);
			};
		});
	}
}
